package com.example.tellwin.home.act;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.example.tellwin.MainApplication;
import com.example.tellwin.MediaActivity;
import com.example.tellwin.PhotoActivity;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseActivty;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.ActDetailEvent;
import com.example.tellwin.home.bean.ActivityDetailContentBean;
import com.example.tellwin.home.contract.UploadWorkContract;
import com.example.tellwin.home.presenter.UploadWorkPresenter;
import com.example.tellwin.utils.GlideUtils;
import com.example.tellwin.utils.ImageUtils;
import com.example.tellwin.utils.LogUtil;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.TakePhotoDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.tellwin.common.Common.MediaRequestCode;
import static com.example.tellwin.common.Common.PhotoAlbumRequestCode;
import static com.example.tellwin.common.Common.TakePhotoRequestCode;
import static com.example.tellwin.common.Common.VocieRequestCode;

public class UploadWorkActivity extends CpBaseActivty implements UploadWorkContract.View {

    @BindView(R.id.act_title_tv)
    TextView actTitleTv;
    @BindView(R.id.add_work_iv)
    ImageView addWorkIv;
    @BindView(R.id.delete_work_iv)
    ImageView deleteWorkIv;
    @BindView(R.id.commit_btn)
    TextView commitBtn;
    @BindView(R.id.voice_view)
    LinearLayout voiceLl;
    @BindView(R.id.play_iv)
    ImageView playIv;

    TakePhotoDialog takePhotoDialog;

    private ActivityDetailContentBean activityDetailContentBean;
    private int workType;//0上传图片1上传音频2上传视频

    private String mediaPath;//临时，不是最终的，请从addWorkIv获取最终地址

    @Inject
    UploadWorkPresenter mPresenter;
    private MediaPlayer mediaPlayer;

    String path ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_work);
        ButterKnife.bind(this);
        initViews();
        initEvents();
        initDatas();
    }

    @Override
    protected void initViews() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);
        commitBtn.setEnabled(false);
    }

    @Override
    protected void initEvents() {

    }

    @Override
    protected void initDatas() {
        setTitle(R.string.upload_work);
        activityDetailContentBean = (ActivityDetailContentBean) getIntent().getSerializableExtra(Common.ACTIVITY);
        workType = activityDetailContentBean.getActivityDetails().getParticipateCondition();
    }

    @OnClick({R.id.commit_btn, R.id.delete_work_iv, R.id.add_work_iv, R.id.voice_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.commit_btn:
                if (path == null) {
                    ToastUtil.show(this, "请先上传作品");
                    return;
                }
                mPresenter.uploadFile(path);
                break;
            case R.id.delete_work_iv:
                addWorkIv.setImageResource(R.mipmap.pic_a);
                deleteWorkIv.setVisibility(View.GONE);
                commitBtn.setEnabled(false);
                playIv.setVisibility(View.GONE);
                path = "";
                break;
            case R.id.add_work_iv:
                if (deleteWorkIv.getVisibility() == View.VISIBLE && !TextUtils.isEmpty(path)) {
                    if (workType == 0) {
                        Intent intent = new Intent(this, PhotoActivity.class);
                        ArrayList<String> photoPaths = new ArrayList<>();
                        photoPaths.add(path);
                        intent.putExtra(Common.PHOTO_PATH, photoPaths);
                        startActivity(intent);
                    } else if (workType == 2) {
                        Intent intent1 = new Intent(this, MediaActivity.class);
                        intent1.putExtra(Common.MEDIA_PATH, path);
                        startActivity(intent1);
                    }else {
                        playVoice();
                    }
                    return;
                }
                if (workType == 0) {
                    if (takePhotoDialog == null) {
                        takePhotoDialog = new TakePhotoDialog(this);
                    }
                    takePhotoDialog.show();
                } else if (workType == 1) {
                    Intent intentRecord = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //添加这一句表示对目标应用临时授权该Uri所代表的文件
                        intentRecord.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    intentRecord.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
                    startActivityForResult(intentRecord, VocieRequestCode);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查该权限是否已经获取
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                                || ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                            // 如果没有授予该权限，就去提示用户请求
                            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 321);
                            ToastUtil.show(MainApplication.getContext(), "请授权！");
                            return;
                        }
                    }

                    Uri fileUri;
                    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    File file = createMediaFile();
                    mediaPath = file.getPath();
                    fileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", file);//这是正确的写法

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                    startActivityForResult(intent, MediaRequestCode);
                }
                break;
            case R.id.voice_view:
                playVoice();
                break;
        }

    }

    private void playVoice() {
        String workPath = (String) addWorkIv.getTag();
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(workPath);//设置播放来源
            mediaPlayer.prepareAsync();//异步准备
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                //异步准备监听
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();//播放
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File createMediaFile() {
        File f = new File(Common.MediaPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".mp4";
        File file = new File(Common.MediaPath, fileName);

        return file;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TakePhotoRequestCode:
                    if (takePhotoDialog != null) {
                        path = takePhotoDialog.getTakePhotoPath();
                        GlideUtils.LoadImage(this, path, addWorkIv);
                        deleteWorkIv.setVisibility(View.VISIBLE);
                        addWorkIv.setTag(path);
                        commitBtn.setEnabled(true);
                    }
                    break;
                case PhotoAlbumRequestCode:
                    if (data != null) {
                        Uri uri = data.getData();
                        path = ImageUtils.uriToRealPath(this, uri);
                        GlideUtils.LoadImage(this, path, addWorkIv);
                        deleteWorkIv.setVisibility(View.VISIBLE);
                        this.path = path;
                        commitBtn.setEnabled(true);
                    }
                    break;
                case MediaRequestCode:
                    LogUtils.e(mediaPath);
                    Glide.with(this).load(Uri.fromFile(new File(mediaPath))).into(addWorkIv);
                    this.path = mediaPath;
                    deleteWorkIv.setVisibility(View.VISIBLE);
                    commitBtn.setEnabled(true);
                    playIv.setVisibility(View.VISIBLE);
                    break;
                case VocieRequestCode:
                    Uri uri = data.getData();
                    if (uri != null) {
                        path = ImageUtils.uriToRealPath(this, uri);
                        LogUtil.e(path);
                        addWorkIv.setImageDrawable(getResources().getDrawable(R.drawable.black_60_corners_4_shape));
                       // addWorkIv.setTag(path);
                       // addWorkIv.setVisibility(View.GONE);
                        deleteWorkIv.setVisibility(View.VISIBLE);
                        commitBtn.setEnabled(true);
                        playIv.setVisibility(View.VISIBLE);
                      //  voiceLl.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
    }

    @Override
    public void uploadFileResult(String url) {
        LogUtils.e(url);
        mPresenter.participateActivity(activityDetailContentBean.getActivityDetails().getActivityId(), url);
    }

    @Override
    public void participateActivityResult() {
        finish();
        EventBus.getDefault().post(new ActDetailEvent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaPlayer!=null){
            mediaPlayer.release();
        }
    }
}
